define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuyou/layui/layui.js'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            var bom_id = Config.ids;
            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                table.render({
                    elem: '#table'
                    ,url:'kuyou/mrps/index'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                        };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,page: true
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,cols: [[
                        {checkbox: true},
                        {field: 'purchase_code', title: __('Purchase_code'),width:180},
                        {field: 'purchase_time', title: __('Purchase_time'),templet: function (d) {
                                return layui.util.toDateString(d.purchase_time*1000,"yyyy-MM-dd");
                            },width:110},
                        {field: 'delivery_time', title: __('Delivery_time'),templet: function (d) {
                                return layui.util.toDateString(d.delivery_time*1000,"yyyy-MM-dd");
                            },width:110},
                        {field: 'createtime', title: __(__('computing time')),templet: function (d) {
                                return layui.util.toDateString(d.createtime*1000,"yyyy-MM-dd HH:mm:ss");
                            },width:180},
                        {field: 'workshop_id', title: __('Workshop_id')},
                        {field: 'number', title: __('Number')},
                        {field: 'all_money', title: __('All_money')},
                        {fixed: 'right', title:__('Operate'), toolbar: '#thisBarDemo', width:250}
                    ]]
                });

                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    var ids = '';
                    $(data).each(function (k,v) {
                        ids+=v.id+',';
                    });
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            Fast.api.open("kuyou/mrps/add?bom_id="+bom_id, __('add to'), {
                                callback:function(value){
                                    Controller.api.bindevent();
                                },
                                area:['90%','90%']
                            });
                            break;
                        case 'delAll':
                            if(data.length<=0){
                                Toastr.error(__('Please select the data to be deleted'));return;
                            }
                            Layer.confirm(
                                __('Are you sure you want to delete the %s selected item?', data.length),
                                {icon: 3, title: __('Warning'), shadeClose: true},
                                function (index) {
                                    Fast.api.ajax("kuyou/mrps/del?ids="+ids, function () {
                                        $('.btn-refresh').click();
                                    },'',true);
                                    Layer.close(index);
                                }
                            );
                            break;
                    }
                });
                //监听行工具事件
                table.on('tool(table)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'del'){
                        var that = this;
                        var top = $(that).offset().top - $(window).scrollTop();
                        var left = $(that).offset().left - $(window).scrollLeft() - 260;
                        if (top + 154 > $(window).height()) {
                            top = top - 154;
                        }
                        if ($(window).width() < 480) {
                            top = left = undefined;
                        }
                        Layer.confirm(
                            __('Are you sure you want to delete this item?'),
                            {icon: 3, title: __('Warning'),offset: [top, left], shadeClose: true},
                            function (index) {
                                $.ajax( {
                                    url: "kuyou/mrps/del",
                                    type: "POST",
                                    data:{'ids':data.id},
                                    success: function(res){
                                        if(res.code==1){
                                            Toastr.success(__('Operation successful'));
                                            setTimeout(function () {
                                                $('.btn-refresh').click();
                                            },1000)
                                        }else{
                                            Toastr.error(res.msg);
                                        }
                                    }
                                });
                                Layer.close(index);
                            }
                        );
                    } else if(obj.event === 'edit'){
                        Fast.api.open("kuyou/mrps/edit?ids="+data.id, __('Material List'),{ area:['90%','90%']});
                    }
                });

                layui.form.on('switch(switchList)', function (obj) {
                    var onoff = this.checked ? '1' : '0';
                    var id = $(this).data('id');
                    $.ajax( {
                        url: "kuyou/mrps/multi",
                        type: "POST",
                        data:{
                            'ids':id,
                            'params':"status="+onoff,
                        },
                        success: function(res){
                            if(res.code==0){
                                Toastr.error(res.msg);
                            }else{
                                Toastr.success(__('Operation successful'));
                            }
                        }
                    });
                });
                layui.form.on('switch(switchLists)', function (obj) {
                    var onoff = this.checked ? '1' : '0';
                    var id = $(this).data('id');
                    $.ajax( {
                        url: "kuyou/mrps/multi",
                        type: "POST",
                        data:{
                            'ids':id,
                            'params':"order_status="+onoff,
                        },
                        success: function(res){
                            if(res.code==0){
                                Toastr.error(res.msg);
                            }else{
                                Toastr.success(__('Operation successful'));
                            }
                        }
                    });
                });
                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1
                        }
                    });
                });
                function getSearch() {
                    var search = {};
                    var purchase_code = $('#purchase_code').val();
                    if(purchase_code!=''){
                        search.purchase_code = purchase_code;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.purchase_code = 'LIKE';
                    return op;
                }
            });
            Controller.api.bindevent();
        },
        add: function () {
            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                table.render({
                    elem: '#chosetable'
                    ,url:'kuyou/Plan/choseplan'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                        };
                    }
                    // ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    , id: 'layuiReload'
                    ,defaultToolbar:""
                    ,where: {purchase_code:''}
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,cols: [[
                        {checkbox: true,width:100},
                        {field: 'goods_code', title: __(__('Product Code')),width:180},
                        {field: 'goods_name', title: __(__('Product Name'))},
                        {field: 'unit_id', title: __(__('Company')),templet: function (d) {
                                return d.unit.name;
                            }},
                        {field: 'purchase', title: __(__('cost'))},
                        {field: 'number', title: __(__('quantity'))},
                    ]]
                    ,done: function(res, curr, count){
                        if(res.total<1){
                            $(".layui-table-main").html('');
                        }
                    }
                });
                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    var ids = '';
                    $(data).each(function (k,v) {
                        ids+=v.id+',';
                    });
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            Fast.api.open("kuyou/mrps/add?bom_id="+bom_id, __('add to'), {
                                callback:function(value){
                                    Controller.api.bindevent();
                                },
                                area:['90%','90%']
                            });
                            break;
                        case 'delAll':
                            if(data.length<=0){
                                Toastr.error(__('Please select the data to be deleted'));return;
                            }
                            Layer.confirm(
                                __('Are you sure you want to delete the %s selected item?', data.length),
                                {icon: 3, title: __('Warning'), shadeClose: true},
                                function (index) {
                                    Fast.api.ajax("kuyou/mrps/del?ids="+ids, function () {
                                        $('.btn-refresh').click();
                                    },'',true);
                                    Layer.close(index);
                                }
                            );
                            break;
                        case 'examine':
                            if(data.length<=0){
                                Toastr.error(__('Please select the data to be audited'));return;
                            }
                            Fast.api.ajax("kuyou/mrps/examine?examine=1&ids="+ids, function () {
                                $('.btn-refresh').click();
                            },'',true);
                            break;
                        case 'examine_f':
                            if(data.length<=0){
                                Toastr.error(__('Please select the data to be de audited'));return;
                            }
                            Fast.api.ajax("kuyou/mrps/examine?examine=2&ids="+ids, function () {
                                $('.btn-refresh').click();
                            },'',true);
                            break;
                    }
                });

                $(document).on("click", "#c-purchase_code", function(){
                    parent.Fast.api.open("kuyou/Plan/choseplan", __('Select Production Plan'),{area:['75%','75%'],callback:function(goodsData){
                            if(goodsData!=undefined){
                                $('#c-purchase_code').val(goodsData[0]['purchase_code']);
                                changeCode();
                            }
                        }});
                });

                function changeCode(){
                    var purchase_code = $('#c-purchase_code').val();
                    table.reload('layuiReload', {
                        where: {purchase_code:purchase_code}
                    });
                }

                $(document).on("click", "#sureBtn", function(){
                    var checkStatus = table.checkStatus('layuiReload');
                    var data = checkStatus.data;
                    if(data.length<1){
                        Toastr.error(__('请选择商品！'));return;
                    }
                    var ids = '';
                    $(data).each(function (k,v) {
                        ids+=v.id+',';
                    });
                    $('#info_id').val(ids);
                    $.ajax( {
                        url: "kuyou/mrps/add",
                        type: "POST",
                        data:$('#add-forms').serialize(),
                        success: function(res){
                            if(res.code==1){
                                Toastr.success(__('Calculation successful'));
                                setTimeout(function () {
                                    parent.location.reload();
                                },1000)
                            }else{
                                Toastr.error(res.msg);
                            }
                        }
                    });
                });
            });
            Controller.api.bindevent();
        },
        edit: function () {
            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;
                var id = $('#id').val();
                table.render({
                    elem: '#edittable'
                    ,url:'kuyou/mrps/edit'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                        };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    , id: 'edittables'
                    ,defaultToolbar:""
                    ,where: {id:id}
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,cols: [[
                        {checkbox: true,width:100},
                        {field: 'goods_code', title: __(__('Product Code')),width:180},
                        {field: 'goods_name', title: __(__('Product Name'))},
                        {field: 'unit_id', title: __(__('Company')),templet: function (d) {
                                return d.unit.name;
                            }},
                        {field: 'purchase', title: __(__('cost'))},
                        {field: 'number', title: __(__('Number of demands'))},
                        {field: 'stock', title: __(__('Inventory quantity'))},
                        {field: 'buy_number', title: __(__('Number of gaps'))},
                    ]]
                });
                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    var ids = '';
                    $(data).each(function (k,v) {
                        ids+=v.id+',';
                    });
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            if(ids==''){
                                Toastr.error(__('Please select the product first'));return;
                            }
                            var arr = new Array();
                            var check_buy_number = false;
                            $(data).each(function (k,v) {
                                if(v.buy_number==''){
                                    check_buy_number = true;
                                }
                                var row = new Array();
                                row['goods_code'] = v.goods_code;
                                row['goods_unit'] = v.unit_id;
                                row['now_buy_number'] = v.buy_number;
                                row['buy_price'] = v.purchase;
                                arr.push(row);
                            });
                            if(check_buy_number){
                                Toastr.error(__('缺口数量需大于0，否则无法生成购货订单！'));return;
                            }
                            var arrstr = arrayToJsonString(arr);
                            $.ajax( {
                                url: "kuyou/mrps/setdata",
                                type: "POST",
                                data:{'row':arrstr},
                                success: function(res){
                                    if(res.code==0){
                                        Toastr.error(res.msg);
                                    }else{
                                        Fast.api.open("kuyou/goods_purchase_order/add?type=2", __('Purchase Order'),{ area:['90%','75%'],});
                                    }
                                }
                            });
                            break;
                    }
                });
                function arrayToJsonString(o) {
                    var len = o.length;
                    var new_arr = new Array();
                    var str = '',strone='',strs='',jsonstr='';
                    for(var i = 0;i<len;i++){
                        new_arr = o[i];
                        for(var k in new_arr){
                            strone += '"'+k+'"'+':'+'"'+new_arr[k]+'"'+',';
                        }
                        str = '{'+strone.substring(0,strone.length-1)+'}';
                        strone='';
                        strs += str+',';
                        new_arr=[];
                    }
                    strs = '['+strs.substring(0,strs.length-1)+']';
                    return strs;
                }
            });
            Controller.api.bindevent(false);
        },
        api: {
            bindevent: function (reloadStatus=true) {
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    if(reloadStatus){
                        parent.location.reload();
                    }else{
                        $('.btn-refresh').click();
                    }
                });
            }
        }
    };
    return Controller;
});
